# 数据库模型文件
from datetime import datetime
from flask_login import UserMixin
from app.extensions import db
from werkzeug.security import generate_password_hash, check_password_hash
from app.models.role import user_roles

class User(UserMixin, db.Model):
    """用户模型"""
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password_hash = db.Column(db.String(255), nullable=False)
    
    # 用户资料字段
    nickname = db.Column(db.String(30), nullable=True)
    bio = db.Column(db.Text, nullable=True)
    age = db.Column(db.Integer, nullable=True)
    gender = db.Column(db.String(10), nullable=True)
    phone = db.Column(db.String(20), nullable=True)
    birth_date = db.Column(db.Date, nullable=True)
    address = db.Column(db.String(200), nullable=True)
    avatar = db.Column(db.String(255), nullable=True)
    interests = db.Column(db.String(200), nullable=True)
    website = db.Column(db.String(255), nullable=True)
    is_public = db.Column(db.Boolean, default=True)
    
    # 系统字段
    is_active = db.Column(db.Boolean, default=True)
    is_admin = db.Column(db.Boolean, default=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 多对多关系：一个用户可以有多个角色
    roles = db.relationship('Role', secondary=user_roles,
                           backref=db.backref('users', lazy='dynamic'))
    
    def __repr__(self):
        return f'<User {self.username}>'
    
    def set_password(self, password):
        """设置密码，进行哈希处理"""
        self.password_hash = generate_password_hash(password)
    
    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)
    
    def to_dict(self):
        """将模型转换为字典"""
        return {
            'id': self.id,
            'username': self.username,
            'email': self.email,
            'nickname': self.nickname,
            'bio': self.bio,
            'age': self.age,
            'gender': self.gender,
            'phone': self.phone,
            'birth_date': self.birth_date.isoformat() if self.birth_date else None,
            'address': self.address,
            'avatar': self.avatar,
            'interests': self.interests,
            'website': self.website,
            'is_public': self.is_public,
            'is_active': self.is_active,
            'is_admin': self.is_admin,
            'roles': [role.name for role in self.roles],
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None
        }
    
    def has_role(self, role_name):
        """检查用户是否拥有特定角色"""
        return any(role.name == role_name for role in self.roles)
    
    def has_permission(self, permission_name):
        """检查用户是否拥有特定权限"""
        for role in self.roles:
            if role.has_permission(permission_name):
                return True
        return False
    
    def add_role(self, role):
        """添加角色到用户"""
        if not self.has_role(role.name):
            self.roles.append(role)
    
    def remove_role(self, role):
        """从用户中移除角色"""
        if self.has_role(role.name):
            self.roles.remove(role)